package com.yungu.swift.api.wxapi;


import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.assets.driver.model.vo.DriverVo;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.common.model.dto.CommonTagDto;
import com.yungu.swift.common.service.CommonTagService;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.MagicConstant;
import com.yungu.swift.constants.OrderConstant;
import com.yungu.swift.order.model.param.ApiOrderListParam;
import com.yungu.swift.order.model.param.ApiOrderNoAnswerCancelParam;
import com.yungu.swift.order.model.param.ApiOrderUuidParam;
import com.yungu.swift.order.model.vo.JsonOrderDetailVo;
import com.yungu.swift.order.model.vo.JsonOrderListVo;
import com.yungu.swift.order.model.vo.OrderEstimateVo;
import com.yungu.swift.order.service.OrderFareService;
import com.yungu.swift.order.service.OrderService;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import com.yungu.swift.utils.ValidateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by cuixiuyin on 2018/5/5.
 */
@RestController
@RequestMapping("/wx/Order")
@Api(value = "【微信】【订单】乘客订单公用接口")
public class WxOrderController {

    @Reference
    private OrderService orderService;
    @Reference
    private OrderFareService orderFareService;

    @Reference
    private CommonTagService commonTagService;


    private ResponseData setOrderValueToSession(String orderUuid, HttpServletRequest request) {
        ResponseData<JsonOrderDetailVo> responseData = orderService.getOrderDetail(orderUuid, null);
        if (responseData.isSuccess()) {
            JsonOrderDetailVo jsonOrderDetailVo = responseData.getData();
            //添加一些信息进入session
            request.getSession().setAttribute("orderUuid", jsonOrderDetailVo.getUuid());
            request.getSession().setAttribute("originDetailAddress", jsonOrderDetailVo.getOriginDetailAddress());
            request.getSession().setAttribute("destDetailAddress", jsonOrderDetailVo.getDestDetailAddress());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (jsonOrderDetailVo.getDeparTime() != null) {
                request.getSession().setAttribute("departTime", formatter.format(jsonOrderDetailVo.getDeparTime()));
            } else {
                request.getSession().setAttribute("departTime", formatter.format(jsonOrderDetailVo.getCreateOn()));
            }
            DriverVo driverVo = jsonOrderDetailVo.getDriver();
            if (null != jsonOrderDetailVo.getDriver()) {
                request.getSession().setAttribute("driverBean", driverVo);
            }
            //存入取消原因
            if (jsonOrderDetailVo.getSubStatus().compareTo(OrderConstant.ORDER_STATUS_DRI_CANCEL_WAIT_FREE) == 0) {
                request.getSession().setAttribute("cancelReason", jsonOrderDetailVo.getCancelReason());
            } else {
                request.getSession().removeAttribute("cancelReason");
            }
            //如果订单类型为500，存入totalFare
            if (jsonOrderDetailVo.getSubStatus().compareTo(OrderConstant.ORDER_STATUS_FARE_CONFIRM) == 0) {
                request.getSession().setAttribute("totalFare", jsonOrderDetailVo.getTotalFare());
            }
            //获取预估价格
            String passengerUuid = (String) request.getSession().getAttribute("passengerUuid");
            ApiOrderUuidParam orderUuidParam = new ApiOrderUuidParam();
            orderUuidParam.setUserUuid(passengerUuid);
            orderUuidParam.setAppid(WxConstants.APPID);
            orderUuidParam.setOrderUuid(orderUuid);
            ResponseData<OrderEstimateVo> fareData = orderFareService.getRealtimeFare(orderUuidParam);
            if (fareData.isSuccess() && fareData.getData() != null) {
                OrderEstimateVo estimateVo = fareData.getData();
                request.getSession().setAttribute("totalFare", estimateVo.getTotalFare());
                request.getSession().setAttribute("lng", estimateVo.getLng());
                request.getSession().setAttribute("lat", estimateVo.getLat());
            }
        }
        return responseData;
    }

    @RequestMapping(value = "/info")
    @ApiOperation(value = "订单详情接口", notes = "订单详情", response = ResponseData.class)
    public ResponseData info(HttpServletRequest request,
                             @ApiParam(name = "orderUuid", value = "订单id", required = true) @RequestParam String orderUuid) {
        if (!StringUtils.isNotEmpty(orderUuid)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "参数错误");
        }
        return setOrderValueToSession(orderUuid, request);
    }

    @RequestMapping(value = "/list")
    @ApiOperation(value = "获取订单列表接口", notes = "")
    public ResponseData<Map<String, Object>> list(@ApiParam(value = "用户ID", name = "passengerUuid") @RequestParam String passengerUuid,
                                                  @ApiParam(name = "nowPage", value = "当前页") @RequestParam(required = false) Integer nowPage) {
        Map<String, Object> map = MapUtils.build(2);
        //获取进行中的订单
        ApiOrderListParam orderListParam = new ApiOrderListParam();
        orderListParam.setUserUuid(passengerUuid);
        orderListParam.setNowPage(nowPage);
        List<JsonOrderListVo> orderDoing = orderService.queryOrderDoing(orderListParam).getData();
        //获取已完成的订单
        List<JsonOrderListVo> orderDone = orderService.queryOrderDone(orderListParam).getData();

        //只有是第一次请求的（nowPage = 1）才返回正在进行中的订单
        if (1 == nowPage || nowPage == null) {
            map.put("orderDoing", orderDoing);
        } else {
            map.put("orderDoing", Collections.emptyList());
        }
        map.put("orderDone", orderDone);
        return ResponseData.buildSuccessResponse("获取成功", map);
    }

    @RequestMapping(value = "/status")
    @ApiOperation(value = "首页获取订单状态", notes = "订单状态", response = ResponseData.class)
    public ResponseData status(@ApiParam(value = "用户ID", name = "passengerUuid") @RequestParam String passengerUuid,
                               HttpServletRequest request) {
        //清空所有缓存
        request.getSession().removeAttribute("actualMobile");
        request.getSession().removeAttribute("orderUuid");
        request.getSession().removeAttribute("originDetailAddress");
        request.getSession().removeAttribute("destDetailAddress");
        request.getSession().removeAttribute("departTime");
        request.getSession().removeAttribute("totalFare");
        request.getSession().removeAttribute("lng");
        request.getSession().removeAttribute("lat");
        ResponseData<Map<String, Object>> responseData = orderService.getOrderStatus(passengerUuid, null);
        if (responseData.isSuccess()) {
            Map<String, Object> map = responseData.getData();
            if ((Integer) map.get(MagicConstant.PARAMS_STATUS) != 0) {
                String orderUuid = (String) map.get("orderUuid");
                setOrderValueToSession(orderUuid, request);
            }
        }
        return responseData;
    }

    @RequestMapping(value = "/saveActualMobile")
    @ApiOperation(value = "保存换乘车人手机", notes = "订单状态", response = ResponseData.class)
    public ResponseData<String> saveActualMobile(HttpServletRequest request,
                                                 @ApiParam(value = "换乘车人手机", name = "actualMobile") @RequestParam String actualMobile) {
        if (!StringUtils.isEmpty(actualMobile) && !ValidateUtils.validateMobile(actualMobile)) {
            request.getSession().removeAttribute("actualMobile");
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "手机号码格式错误");
        }
        request.getSession().setAttribute("actualMobile", actualMobile);
        return ResponseData.buildSuccessResponse("actualMobile", actualMobile);
    }

    @RequestMapping(value = "/cancelOrder")
    @ApiOperation(value = "微信行程未确定取消订单", notes = "取消订单", response = ResponseData.class)
    public ResponseData<Boolean> cancel(@ApiParam(name = "orderUuid", value = "订单", required = true) @RequestParam String orderUuid,
                                        HttpServletRequest request) {
        if (StringUtils.isEmpty(orderUuid)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "参数错误");
        }
        request.getSession().setAttribute("orderUuid", orderUuid);
        ApiOrderNoAnswerCancelParam noAnswerCancelParam = new ApiOrderNoAnswerCancelParam();
        noAnswerCancelParam.setType(1);
        noAnswerCancelParam.setOrderUuid(orderUuid);
        return orderService.noConfirmCancel(noAnswerCancelParam);
    }

    @RequestMapping(value = "/canceConfirmlOrder")
    @ApiOperation(value = "行程确定取消订单", notes = "取消订单", response = ResponseData.class)
    public ResponseData<Boolean> confirmCancel(@ApiParam(name = "orderUuid", value = "订单", required = true) @RequestParam String orderUuid,
                                               @ApiParam(name = "cancelMsg", value = "取消原因") @RequestParam(required = false) String cancelMsg,
                                               HttpServletRequest request) {
        if (StringUtils.isEmpty(orderUuid)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "参数错误");
        }
        request.getSession().setAttribute("orderUuid", orderUuid);
        request.getSession().setAttribute("cancelReason", cancelMsg);
        return orderService.pasConfirmCancel(orderUuid, cancelMsg);
    }

    @RequestMapping("/getCancelTag")
    @ApiOperation(value = "获取取消原因列表", response = ResponseData.class, notes = "list")
    public ResponseData listOfCancelMsg(HttpServletRequest request) {
        Map<String, Object> map = MapUtils.build(4);
        map.put("tagType", CommonConstant.TAG_TYPE_CANCEL);
        map.put("tagStatus", MagicConstant.INT_ONE);
        map.put("identity", CommonConstant.PASSENGER);
        map.put("appid", WxConstants.APPID);
        List<CommonTagDto> commonTagDtoList = commonTagService.list(map).getData();
        if (commonTagDtoList != null) {
            request.getSession().setAttribute("commonTagDtoList", commonTagDtoList);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "获取不到数据");
    }


}
